class User < ActiveRecord::Base

  has_many :twitter_profiles
  has_many :geopositions

  # friendship:
  has_many :friendships
  has_many :friends, :through => :friendships
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user

  validates :default_profile, :presence => true
  validates :token, :uniqueness => true

  attr_protected :friendships, :friends, :inverse_friendships, :inverse_friends

  def all_information
    { :id => self.id,
      :name => self.name,
      :image => self.image,
      :screen_name => self.screen_name,
      :location => self.location,
      :description => self.description,
      :website => self.website }
  end

  def self.token_valid?( token )
    count = User.where(:token => token).count
    if count == 1
      true
    else
      false
    end
  end

  def are_friends?(user)
    if self == user
      false
    else
      self.friends.include?(user) and user.friends.include?(self)
    end
  end

  def request_friendship(user)
    unless self.friends.include?(user)
      self.friendships.create(:friend_id => user.id)
    else
      false
    end
  end

  def friend_requests
    self.inverse_friends
  end

  def all_friends
    friends = Array.new
    for request in self.friends do
      if request.are_friends?(self)
        friends.push request
      end
    end
    friends
  end

  def last_longitude
    self.geopositions.last.longitude
  end

  def last_latitude
    self.geopositions.last.latitude
  end

  # info methods:
    def website
      if twitter
        twitter_profile.website
      else
        "NDP"
      end
    end
    def location
      if twitter
        twitter_profile.location
      else
        "NDP"
      end
    end
    def description
      if twitter
        twitter_profile.description
      else
        "NDP"
      end
    end
    def screen_name
      if twitter
        twitter_profile.screen_name
      else
        "No default profile"
      end
    end
    def name
      if twitter
        twitter_profile.name
      else
        "No dafault profile"
      end
    end
    def image
      if twitter
        twitter_profile.image
      else
        "No default profile"
      end
    end
    # aliases:
      def nombre
        name
      end

  private
    def twitter
      self.default_profile == "twitter"
    end
    def twitter_profile
      @twitter_profile ||= self.twitter_profiles.first
    end
end
